from PIL import Image, ImageDraw, ImageFont
import exifread
import argparse
from PIL import Image, ImageDraw, ImageFont

def get_exif_maker(image_path):
    """提取图片EXIF信息中的制造商(maker)"""
    with open(image_path, 'rb') as f:
        tags = exifread.process_file(f)
        maker_tag = 'Image Make'
        if maker_tag in tags:
            return str(tags[maker_tag]).strip()
    return None

def get_exif_model(image_path):
    """提取图片EXIF信息中的型号(model)"""
    with open(image_path, 'rb') as f:
        tags = exifread.process_file(f)
        model_tag = 'Image Model'
        if model_tag in tags:
            return str(tags[model_tag]).strip()
    return None

def print_all_exif(image_path):
    """打印图片的所有EXIF信息"""
    with open(image_path, 'rb') as f:
        tags = exifread.process_file(f)
        print("所有EXIF信息:")
        for tag in tags:
            print(f"{tag}: {tags[tag]}")

def get_capture_date(image_path):
    """提取图片的拍摄日期"""
    with open(image_path, 'rb') as f:
        tags = exifread.process_file(f)
        # 尝试常见的日期标签
        date_tags = ["EXIF DateTimeOriginal", "EXIF DateTimeDigitized", "Image DateTime"]
        for tag in date_tags:
            if tag in tags:
                return str(tags[tag])
    return "未知日期"

def add_watermark(input_path, output_path, maker_text, date_text):
    """在图片左下角添加水印"""
    # 打开图片并转换为RGBA模式以支持透明度
    with Image.open(input_path).convert("RGBA") as img:
        draw = ImageDraw.Draw(img)
        width, height = img.size

        # 设置水印字体和大小
        # 根据图片尺寸动态调整字体大小（手机水印通常较小）
        font_size = int(min(width, height) * 0.05)  # 图片最小边的5%（增加一倍的水印大小）

        # 尝试加载系统字体，支持中文显示
        try:
            # 尝试不同系统的常见字体路径
            font_paths = [
                "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",  # Linux
                "/System/Library/Fonts/PingFang.ttc",  # macOS
                "C:\\Windows\\Fonts\\simhei.ttf",  # Windows
                "/usr/share/fonts/truetype/freefont/FreeSans.ttf"  # 通用后备
            ]
            font = None
            for path in font_paths:
                try:
                    font = ImageFont.truetype(path, font_size)
                    break
                except:
                    continue
            if not font:
                font = ImageFont.load_default()
        except:
            font = ImageFont.load_default()

        # 计算文本尺寸
        bbox = draw.textbbox((0, 0), maker_text, font=font)
        text_width = bbox[2] - bbox[0]
        text_height = bbox[3] - bbox[1]

        # 设置行间距
        line_spacing = int(text_height * 0.3)  # 行间距为文本高度的30%

        # 设置水印位置（左下角，带边距）
        margin = int(min(width, height) * 0.02)  # 边距为图片最小边的2%
        x = margin
        # 计算总文本高度（两行文本 + 行间距）
        total_text_height = text_height * 2 + line_spacing
        y = height - total_text_height - margin

        # 添加半透明白色水印（带轻微黑色描边增加可读性）
        # 添加制造商水印（带描边）
        # 描边
        draw.text((x-1, y-1), maker_text, font=font, fill=(0, 0, 0, 100))
        draw.text((x+1, y-1), maker_text, font=font, fill=(0, 0, 0, 100))
        draw.text((x-1, y+1), maker_text, font=font, fill=(0, 0, 0, 100))
        draw.text((x+1, y+1), maker_text, font=font, fill=(0, 0, 0, 100))
        # 主文本
        draw.text((x, y), maker_text, font=font, fill=(255, 255, 255, 200))
        
        # 计算日期文本位置（制造商下方）
        date_y = y + text_height + line_spacing
        
        # 添加日期水印（带描边）
        # 描边
        draw.text((x-1, date_y-1), date_text, font=font, fill=(0, 0, 0, 100))
        draw.text((x+1, date_y-1), date_text, font=font, fill=(0, 0, 0, 100))
        draw.text((x-1, date_y+1), date_text, font=font, fill=(0, 0, 0, 100))
        draw.text((x+1, date_y+1), date_text, font=font, fill=(0, 0, 0, 100))
        # 主文本
        draw.text((x, date_y), date_text, font=font, fill=(255, 255, 255, 200))

        # 转换回RGB模式并保存
        img.convert("RGB").save(output_path, quality=95)

def main():
    parser = argparse.ArgumentParser(description='为图片添加EXIF制造商信息和日期作为水印')
    parser.add_argument('input', help='输入图片路径')
    parser.add_argument('output', help='输出图片路径')
    args = parser.parse_args()

    # 打印所有EXIF信息
    print_all_exif(args.input)

    # 获取制造商信息
    maker = get_exif_maker(args.input)
    if not maker:
        print("错误: 无法从图片中获取制造商信息")
        return

    # 获取型号信息
    model = get_exif_model(args.input)
    if model:
        maker = f"{maker} {model}"  # 将model添加到maker后面

    # 获取拍摄日期
    capture_date = get_capture_date(args.input)

    # 添加水印（包含制造商和日期）
    add_watermark(args.input, args.output, maker, capture_date)
    print(f"成功: 水印已添加，输出文件: {args.output}")

if __name__ == "__main__":
    main()
